package com.taoz.mianshiwa.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taoz.mianshiwa.common.ErrorCode;
import com.taoz.mianshiwa.constant.SortOrder;
import com.taoz.mianshiwa.constant.RedisConstant;
import com.taoz.mianshiwa.constant.UserConstant;
import com.taoz.mianshiwa.exception.BusinessException;
import com.taoz.mianshiwa.exception.ThrowUtils;
import com.taoz.mianshiwa.mapper.UserMapper;
import com.taoz.mianshiwa.model.dto.user.UserQueryRequest;
import com.taoz.mianshiwa.model.entity.User;
import com.taoz.mianshiwa.model.enums.UserRoleEnum;
import com.taoz.mianshiwa.model.vo.LoginUserVO;
import com.taoz.mianshiwa.model.vo.UserVO;
import com.taoz.mianshiwa.satoken.DeviceUtil;
import com.taoz.mianshiwa.service.UserService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.LocalDate;
import org.redisson.api.RBitSet;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import java.util.stream.Collectors;
import static com.taoz.mianshiwa.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户服务实现
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    /**
     * 盐值，混淆密码
     * 可以有效防止密码被破解
     * 如果没有SALT，那么密码和加密密码存在映射关系，存在通过加密密码反解出密码的可能性
     * 加了SALT后，反解出来的密码是SALT+密码，仍然无法登录
     */
    public static final String SALT = "taoz";

    @Resource
    private RedissonClient redissonClient;

    @Override
    public List<Integer> getSignInList(Integer year, Long userId) {
        String key = RedisConstant.getUserSignInKey(year, userId);
        RBitSet bitSet = redissonClient.getBitSet(key);
        BitSet record = bitSet.asBitSet();

        int st = 0, p;
        ArrayList<Integer> signInList = new ArrayList<>();
        while ((p = record.nextSetBit(st)) != -1) {
            signInList.add(p);
            st = p + 1;
        }
        return signInList;
    }

    @Override
    public boolean signIn(Long userId) {
        LocalDate localDate = new LocalDate();
        String key = RedisConstant.getUserSignInKey(localDate.getYear(), userId);
        RBitSet bitSet = redissonClient.getBitSet(key);
        bitSet.set(localDate.getDayOfYear(), true);
        return true;
    }

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        // 1. 参数校验
        ThrowUtils.throwIf(StringUtils.isAnyBlank(userAccount, userPassword, checkPassword), ErrorCode.PARAMS_ERROR, "参数为空");
        ThrowUtils.throwIf(userAccount.length() < 4, ErrorCode.PARAMS_ERROR, "用户账号过短");
        ThrowUtils.throwIf(userPassword.length() < 8 || checkPassword.length() < 8, ErrorCode.PARAMS_ERROR, "用户密码过短");
        ThrowUtils.throwIf(!userPassword.equals(checkPassword), ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");


        synchronized (userAccount.intern()) {
            // 账户不能重复
            // 使用数据库的覆盖索引，避免回表查询
            User user = lambdaQuery().select(User::getUserAccount).eq(User::getUserAccount, userAccount).one();
            ThrowUtils.throwIf(user != null, ErrorCode.PARAMS_ERROR, "账号已存在");

            // 存入数据库的密码需要加密处理，在后端层面进行加密操作
            String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

            // 插入数据
            User newUser = new User();
            newUser.setUserAccount(userAccount);
            newUser.setUserPassword(encryptPassword);
            // mp的save方法如果save成功会将生成的Id注入给newUser
            boolean ok = save(newUser);
            ThrowUtils.throwIf(!ok, ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");

            return newUser.getId();
        }
    }

    @Override
    public LoginUserVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 参数校验
        ThrowUtils.throwIf(StringUtils.isAnyBlank(userAccount, userPassword), ErrorCode.PARAMS_ERROR, "账号和密码不能为null");
        ThrowUtils.throwIf(userAccount.length() < 4 || userPassword.length() < 8, ErrorCode.PARAMS_ERROR, "账号或密码过短");

        // 查询用户是否合法
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        User user = lambdaQuery().eq(User::getUserAccount, userAccount).eq(User::getUserPassword, encryptPassword).one();
        ThrowUtils.throwIf(user == null, ErrorCode.PARAMS_ERROR, "账号或密码错误");
        // 用户为 "ban" 禁止登录
        ThrowUtils.throwIf(user.getUserRole().equals(UserConstant.BAN_ROLE), ErrorCode.FORBIDDEN_ERROR, "用户已被封禁");

        // 登录成功，记录该登录用户信息并设置客户端token
        StpUtil.login(user.getId(), DeviceUtil.getClientDevice(request));
        // 缓存登录用户状态
        StpUtil.getSession().set(USER_LOGIN_STATE, user);

        return this.getLoginUserVO(user);
    }

    /**
     * 获取当前登录用户
     */
    @Override
    public User getLoginUser() {
        // 先判断是否已登录
        Object loginUserId = StpUtil.getLoginIdDefaultNull();
        ThrowUtils.throwIf(loginUserId == null, ErrorCode.NOT_LOGIN_ERROR, "用户未登录");

        // 查询并返回登录用户
        User user = getById(Long.parseLong(String.valueOf(loginUserId)));
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_LOGIN_ERROR, "用户不存在");
        StpUtil.getSession().set(USER_LOGIN_STATE, user);

        return user;
    }

    /**
     * 用户注销
     */
    @Override
    public boolean userLogout(HttpServletRequest request) {
        // 移除登录态，删除客户端和服务端的token信息，如果未登录不会执行任何操作
        StpUtil.logout();

        return true;
    }

    @Override
    public LoginUserVO getLoginUserVO(User user) {
        // 参数校验
        if (user == null) {
            return null;
        }

        // 将对象属性copy到VO对象
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtils.copyProperties(user, loginUserVO);

        return loginUserVO;
    }

    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public List<UserVO> getUserVO(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream().map(this::getUserVO).collect(Collectors.toList());
    }

    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR);

        Long id = userQueryRequest.getId();
        String userAccount = userQueryRequest.getUserAccount();
        String userName = userQueryRequest.getUserName();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(id != null, "id", id);
        queryWrapper.eq(StringUtils.isNotBlank(userAccount), "userAccount", userAccount);
        queryWrapper.like(StringUtils.isNotBlank(userName), "userName", userName);
        queryWrapper.eq(StringUtils.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.orderBy(true, sortOrder.equals(SortOrder.ASC), sortField);

        return queryWrapper;
    }
}
